<template>
	<transition>
		<div
			@click="handleClickModalClose"
			class="dialog-com w-full h-full fixed top-0 left-0 z-50 flex justify-center pb-5"
			v-show="dialogVisible">
			<div
				class="dialog h-fit bg-white rounded-md mt-40 shadow-lg pb-4"
				:style="{ width: dialogWidth }">
				<slot name="header">
					<div class="title w-full py-3 px-4 flex justify-between items-center">
						<div class="title-content text-base text-gray-700 tracking-wider">
							{{ title }}
						</div>
						<div
							title="关闭"
							v-show="showClose"
							class="close w-fit h-fit flex justify-center items-center cursor-pointer text-gray-500 hover:text-blue-500">
							<icon
								:size="28"
								@click="dialogVisible = false"
								name="material-symbols-light:close-small-rounded" />
						</div>
					</div>
				</slot>
				<div class="content px-4 pb-5 pt-3">
					<slot> </slot>
				</div>
				<div class="footer pt-5 px-4">
					<slot name="footer"> </slot>
				</div>
			</div>
		</div>
	</transition>
</template>

<script lang="ts">
export default defineComponent({
	name: 'DialogCom',
	props: {
		modelValue: {
			type: Boolean,
			required: true,
		},
		title: {
			type: String,
			default: 'Tips',
		},
		clickModalClose: {
			type: Boolean,
			default: false,
		},
		showClose: {
			type: Boolean,
			default: true,
		},
	},
	emits: ['update:modelValue'],
	setup(props, { emit }) {
		// 控制弹窗显示隐藏
		const dialogVisible = ref<boolean>(props.modelValue);
		watch(dialogVisible, (newVal: boolean) => {
			emit('update:modelValue', newVal);
			if (newVal) {
				nextTick(() => {
					document.body.style.overflow = 'hidden';
				});
			} else {
				nextTick(() => {
					document.body.style.overflow = 'auto';
				});
			}
		});
		watch(
			() => props.modelValue,
			(newVal: boolean) => {
				dialogVisible.value = newVal;
			}
		);

		// 点击模态框关闭弹窗
		const handleClickModalClose = (): void => {
			if (props.clickModalClose) {
				dialogVisible.value = false;
			}
		};

		// 当前屏幕宽度
		const screenWidth = ref<number>(900);
		// 弹窗宽度
		const dialogWidth = computed(() => {
			if (screenWidth.value <= 880) {
				return '95%';
			}
			return '500px';
		});

		onMounted(() => {
			screenWidth.value = window.innerWidth;

			window.addEventListener('resize', () => {
				screenWidth.value = window.innerWidth;
			});
		});

		onBeforeUnmount(() => {
			window.removeEventListener('resize', () => {});
		});

		return {
			dialogWidth,
			dialogVisible,
			handleClickModalClose,
		};
	},
});
</script>

<style lang="scss" scoped>
.dialog-com {
	overflow-y: scroll;
	background-color: rgba(0, 0, 0, 0.5);

	&::-webkit-scrollbar {
		width: 5px;
	}

	&::-webkit-scrollbar-thumb {
		cursor: pointer;
		border-radius: 5px;
		background-color: #409eff;
	}
}
</style>
